package cn.xf.common.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class BeanUtil extends BeanUtils {

    public static <T> T newInstance(Class<?> clazz) {
        return (T) instantiateClass(clazz);
    }

    public static <T> List<T> convert(Collection<?> sources, Class<T> targetClass) {

        if (CollectionUtils.isEmpty(sources)) {

            return new ArrayList<>();
        }
        return sources.stream().map(source -> convert(source, targetClass)).collect(Collectors.toList());
    }

    public static <T> T convert(Object source, Class<T> targetClass) {
        if (source == null) {
            return null;
        }
        if (targetClass == null) {
            return null;
        }

        T target = instantiateClass(targetClass);
        copyProperties(source, target);
        return target;
    }

    public static <T> T convert(Object source, Class<T> targetClass, String... ignoredProperties) {

        if (source == null) {
            return null;
        }
        if (targetClass == null) {
            return null;
        }

        T target = instantiateClass(targetClass);
        copyProperties(source, target, ignoredProperties);
        return target;
    }

    public static Map<String, Object> toMap(Object bean) {
        return BeanMap.create(bean);
    }

    public static <T> T toBean(Map<String, Object> beanMap, Class<T> valueType) {
        T bean = newInstance(valueType);
        BeanMap.create(bean).putAll(beanMap);
        return bean;
    }
}
